const PERFIX = "room"
module.exports = (app)=>{
  return async(ctx,next)=>{
    const { app,socket,logger,helper } = ctx
    const id = socket.id
    const nsp =  app.io.of('/')
    const query = socket.handshake.query

    const { room,userId } = query

    const rooms = [ room ]
    logger.debug('#user_info',id,room,userId)

    const tick = (id,msg) =>{
      logger.debug("#tick",id,msg)
      socket.emit(id,helper.parseMsg('deny',msg))
      nsp.adapter.remoteDisconnect(id,true,err=>{
        logger.error(err)
      })
    }

    //const hashRoom = await
    //logger.debug("#has_exist")

    //加入房间
    logger.debug("#join",room)
    socket.join(room)
    nsp.adapter.clients(rooms,(err,clients) =>{
      logger.debug("#online_join",clients)

      nsp.to(room).emit("online",{
        clients,
        action:"join",
        target:"participator",
        message:`User(${id}) joined`
      })
    })

    await next()

    logger.debug("#leave",room)
    nsp.adapter.clients(rooms,(err,clients)=>{
      logger.debug('#online_leave',clients)
      nsp.to(room).emit('online',{
        clients,
        action:"leave",
        target:"participator",
        message:`User(${id}) leaved`
      })
    })
  }
}